package m.fun.action;

import m.appserver.ActionRedirect;
import m.base.action.BaseAction;
import m.base.action.BaseStatusAction;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.fun.model.AskDetail;
import m.fun.model.AskInfo;
import m.fun.service.AskInfoService;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.store.action.GuestInfoAction;
import m.store.action.SaleInfoAction;
import m.store.model.GuestInfo;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.sql.SQLException;
import java.util.List;

@ActionMeta(name = "fun/askInfo")
public class AskInfoAction extends BaseStatusAction {
    private AskInfo model;
    private List<AskDetail> details;
    private void verifyFunc() throws Exception {
        if(!LevelUtil.offerFunc()){
            throw new MException(this.getClass(),"当前商户未开通报价单功能")
                    .setRedirect(LevelUtil.toErrorPage("询价列表需要开通报价单功能，当前商户未开通！",false));
        }
    }
    @RequestMeta(transaction = true,logTitle = "询价",logDescription = "提交询价信息")
    public JSONMessage submit() throws MException, SQLException {
        getService(AskInfoService.class).submit(model,details);
        return new JSONMessage(0,"提交成功")
                .push("oid",model.getOid());
    }
    @RequestMeta(logTitle = "询价",logDescription = "保存询价关联客户")
    public JSONMessage doSaveGuest() throws MException {
        if(ObjectUtil.isEmptyOid(model.getGuest())) throw new MException(this.getClass(),"请选择关联客户");
        ModelUpdateUtil.updateModel(model,"guest.oid");
        return new JSONMessage(0,"保存成功");
    }
    @RequestMeta(logTitle = "询价",logDescription = "询价生成销售信息")
    public JSONMessage doBuildSaleInfo() throws Exception {
        getService(AskInfoService.class).buildSaleInfo(model.getOid());
        return JSONMessage.success("生成成功")
            .push("model",ModelQueryList.getModel(AskInfo.class,model.getOid(),"*","guest.name","sale.orderNo"));
    }
    @RequestMeta(params = {"oid"})
    public ActionRedirect toAddGuest(String oid) throws Exception {
        AskInfo model= ModelQueryList.getModel(AskInfo.class,oid,"*");
        GuestInfo guest=new GuestInfo();
        guest.setType(model.getType());
        if(GuestInfo.Type_Company.equals(guest.getType())) {
            guest.setName(model.getName());
        }else{
            guest.setName(model.getDutyUser());
        }
        guest.setDutyUser(model.getDutyUser());
        guest.setTel(model.getTel());
        guest.setAddress(model.getAddress());
        guest.setDescription(model.getDescription());
        return new ActionRedirect(GuestInfoAction.class,"toEdit", new JSONMessage().push("model",guest));
    }

    /*
     * 查看询价信息
     */
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.name","sale.orderNo");
        }else{
            throw new MException(this.getClass(),"");
        }
        ModelForm form = new ModelForm("询价信息");
        form.addItem(
            FormHtml.inputStyle("类型","{{dict('m.fun.model.AskInfo!type',model.type)}}"),
            FormHtml.inputStyle("公司名称","{{model.name}}").setSpan(2),
            FormHtml.inputStyle("负责人","{{model.dutyUser}}"),
            FormHtml.inputStyle("联系电话","{{model.tel}}"),
            FormHtml.inputStyle("提交时间","{{model.submitDate}}"),
            FormHtml.inputStyle("收货地址","{{model.address}}").setSpan(2),
            FormTest.test("model.buildStatus=='"+AskInfo.Build_No+"'",
                FormInput.selectOneModel("关联客户","model","guest","'action/store/guestInfo/selectOneGuest'",1300,"<a @click=\"viewGuest\">{{model.guest.name}}</a>")
            ),
            FormTest.test("model.buildStatus=='"+AskInfo.Build_Done+"'",
                FormHtml.inputStyle("关联客户","<a @click=\"viewGuest\">{{model.guest.name}}</a>")
            ),
            FormHtml.inputStyle("需求备注","{{model.description}}").setSpan(2),
            FormTest.test("model.buildStatus=='"+AskInfo.Build_No+"'",
                FormHtml.ins("出库订单", FormButton.pri("生成出库信息","doBuildSaleInfo").setConfirm("仅生成已选择库存的记录，后续可在出库登记继续编辑，确认要生成吗？"))
            ),
            FormTest.test("model.buildStatus=='"+AskInfo.Build_Done+"'",
                FormHtml.inputStyle("出库订单","<a @click=\"viewSale\">{{model.sale.orderNo}}</a>")
            )
        )
        .addData("model",model)
        .addButton(
            FormButton.gho("生成新客户","toAddGuest").setTest("model.buildStatus=='"+AskInfo.Build_No+"'"),
            FormButton.pri("保存关联客户","doSaveGuest").setTest("model.buildStatus=='"+AskInfo.Build_No+"'")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.toModal("toAddGuest",actionUrl("toAddGuest"),"{oid:this.model.oid}",1000),
            FormEvent.doJson("doSaveGuest",actionUrl("doSaveGuest"),"{model:this.model}"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300),
            FormEvent.doJson("doBuildSaleInfo",actionUrl("doBuildSaleInfo"),"{model:this.model}")
                .fillData("model").success("loadDetailPage"),
            FormEvent.toModal("viewSale",actionUrl(SaleInfoAction.class,"toView"),"{model:{oid:this.model.sale.oid}}",1200)
        );
        LoadPage form1=new LoadPage("loadDetailPage",actionUrl(AskDetailAction.class,"detailList"),"{params:{'ask.oid':this.model.oid}}");
        form1.setMounted("this.loadDetailPage()");
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    /*
     * 询价列表
     */
    public VueResult myAskList() throws Exception {
        verifyFunc();
        VueListResult result=getVueListResult("询价列表",AskInfo.class,actionUrl("myAskList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("类型", "type", 100, true).setDictType("m.fun.model.AskInfo!type"));
        result.addCol(toTextColumn("公司名称", "name", 120, true));
        result.addCol(toTextColumn("负责人", "dutyUser",100,true));
        result.addCol(toTextColumn("联系电话", "tel", 110, true));
        result.addCol(toTextColumn("收货地址", "address", 130, true));
        result.addCol(toTextColumn("需求备注", "description", 150, true));
        result.addCol(toDateTimeColumn("提交时间", "submitDate", 130, true));
        result.addCol(toTextColumn("关联客户","guest.name",130,true));
        result.addCol(toTextColumn("生成状态", "buildStatus", 100, true).setDictType("m.fun.model.AskInfo!buildStatus"));
        result.addCol(toLinkColumn("出库单号", "sale.orderNo", 120, true,
            new ListEvent(actionUrl(SaleInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","sale.oid")
        ));
        result.addCol(toStatusColumn(true,true));
        result.addCol(toSpaceColumn("操作", 100,
            ListElement.test("record.status=='0'&&record.buildStatus=='"+AskInfo.Build_No+"'",
                ListButton.modal("询价确认", ButtonType.PRIMARY,actionUrl("toEdit"),1100, SuccessMethod.MUST_REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='0'&&record.buildStatus=='"+AskInfo.Build_Done+"'",
                ListButton.modal("查看", ButtonType.GHOST,actionUrl("toEdit"),1100, SuccessMethod.MUST_REFRESH)
                    .addParam("model.oid","oid")
            )
        ).setFixed(Align.RIGHT));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("user.oid",PowerUtil.getSessionUserOid()));
        result.addOrder(QueryOrder.desc("submitDate"));
        return result;
    }

    @Override
    public String[] getStatusPower() {
        return new String[0];
    }

    public AskInfo getModel() {
        return model;
    }

    public void setModel(AskInfo model) {
        this.model = model;
    }

    public List<AskDetail> getDetails() {
        return details;
    }

    public void setDetails(List<AskDetail> details) {
        this.details = details;
    }
}
